/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javalens.gui;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javalens.astronomy.Event;
import javalens.astronomy.LightCurve;
import javalens.io.OutputCSV;
import javalens.rwrapper.PlotLib;
import javalens.util.CalculationException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 *
 * @author vermaak
 */
public class CreateCurvePanel extends JPanel implements ActionListener {

    private JButton createCurveButton = new JButton("Create Curve");
    private JButton saveFileButton = new JButton("Save CSV");
    private CurveInputPanel curvePanel = new CurveInputPanel();
    private BinaryLensInputPanel eventPanel = new BinaryLensInputPanel();
    private JFileChooser fileChooser = new JFileChooser();
    private LightCurve resultingCurve;

    public CreateCurvePanel() {
        super();
        setLayout(new GridLayout(0, 2));
        add(eventPanel);
        add(curvePanel);
        add(createCurveButton);
        add(saveFileButton);
        saveFileButton.addActionListener(this);
        createCurveButton.addActionListener(this);
    }

    public void actionPerformed(ActionEvent arg0) {
        if (arg0.getSource() instanceof JButton) {
            if (arg0.getSource().equals(createCurveButton)) {
                Event event = eventPanel.getEvent();
                CurveInputData data = curvePanel.getData();
                resultingCurve = null;
                if (event != null && data != null) {
                    try {
                        resultingCurve = LightCurve.createRegularTimeCurve(data.getStartDay(), data.getEndDay(), data.getNPoints(), event);
                        PlotLib.pausedPlot(resultingCurve);
                    } catch (CalculationException ex) {
                        Logger.getLogger(CreateCurvePanel.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            } else if (arg0.getSource().equals(saveFileButton)) {
                int result = fileChooser.showSaveDialog(this);
                if (result == JFileChooser.APPROVE_OPTION) {
                    File file = fileChooser.getSelectedFile();
                    OutputCSV output = new OutputCSV(file, resultingCurve);
                    try {
                        output.save();
                    } catch (IOException ex) {
                        Logger.getLogger(CreateCurvePanel.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    }
}
